import React, { useState, useCallback, useEffect } from 'react';
import { TextArea, Button,Image } from '@douyinfe/semi-ui';
import { IconPlus, IconMinus } from '@douyinfe/semi-icons';
import { Slider } from '@arco-design/web-react';
import { useImageUpload } from '@/hooks/useImageUpload';
import { clickSelect,boxSelect,smearSelect,partitionSelect,mainSelect } from '@/api/filmRoto';
import add_gray from "@/assets/images/add_gray.svg";
import person_Subject from "@/assets/images/imageEdit/person_Subject.svg";
import general_Subject from "@/assets/images/imageEdit/general_Subject.svg";
import vector from "@/assets/images/vector.svg";
import folder from "@/assets/images/folder.svg";
import styles from "./index.module.scss";
import TimeRangeSelector from './components/time-range-selector';
import ToolButtons from './components/ToolButtons';
import HistoryModal from './components/HistoryModal';

export default function MainEdit({ 
  selectedTool,
  onToolChange,
  toolSize,
  onToolSizeChange,
  hasDataToSubmit,
  selectedPoints,
  selectGreenPoints,
  selectionRects,
  brushStrokes,
  canvasDrawingRef,
  erasureText,
  setErasureText,
  onShowStateChange,
  currentVideo,
  step,
  onStepChange,
  segments = [],
  selectedSegmentId,
  onAddSegment,
  onDeleteSegment,
  onSegmentClick,
  onSegmentStateUpdate,
  selectedPreviewMode,
  hasPreviewVideo,
  onSyntheticVideo
}) {
  const [historyModal, setHistoryModal] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [selectedPreset, setSelectedPreset] = useState('person'); // 预设项选择状态
  const [startTime, setStartTime] = useState('0:00:00:00');
  const [endTime, setEndTime] = useState('0:00:00:00');
  const [showAppliedProject, setShowAppliedProject] = useState(false); // 控制已应用项目的显示
  
  // 使用图片上传hook
  const { handleUpload: uploadFile } = useImageUpload({});

  // 监听选中片段变化，更新时间显示
  useEffect(() => {
    const selectedSegment = segments.find(segment => segment.selectId === selectedSegmentId);
    if (selectedSegment) {
      setStartTime(selectedSegment.startTime || '0:00:00:00');
      setEndTime(selectedSegment.endTime || '0:00:00:00');
    } else {
      setStartTime('0:00:00:00');
      setEndTime('0:00:00:00');
    }
  }, [selectedSegmentId, segments]);

  // 预设项点击处理函数
  const handlePresetClick = (presetType) => {
    setSelectedPreset(presetType);
  };

  // 视频合成处理函数
  const handleSyntheticVideo = () => {
    // 调用父组件的合成函数
    if (onSyntheticVideo) {
      onSyntheticVideo();
    }
  };

  // 上一步处理函数
  const handlePrevStep = () => {
    if (step === 2) {
      onStepChange(1);
      if (onShowStateChange) {
        onShowStateChange({
          showLayerHistory: true,
          showHistory: false,
          showBottom: true
        });
      }
    } else if (step === 1) {
      onStepChange(0);
      if (onShowStateChange) {
        onShowStateChange({
          showLayerHistory: false,
          showHistory: true,
          showBottom: false,
          showMainEdit: false
        });
      }
    }
  };

  // 获取当前选中片段的时间信息
  const getSelectedSegmentTime = () => {
    if (!selectedSegmentId || !segments.length) {
      return { startStamp: '', endStamp: '' };
    }
    
    const selectedSegment = segments.find(segment => segment.selectId === selectedSegmentId);
    if (!selectedSegment) {
      return { startStamp: '', endStamp: '' };
    }
    
    return {
      startStamp: selectedSegment.startTime || '',
      endStamp: selectedSegment.endTime || ''
    };
  };

  // 提交任务处理函数
  const handleSubmitTask = async () => {
    try {
      const { startStamp, endStamp } = getSelectedSegmentTime();
      onSegmentStateUpdate('SUBMITTED');
      if (selectedTool === 'press' && selectedPoints.length > 0) {
        // 原有点选工具提交逻辑（暂时注释）
         const requestData = {
           targetVideoUrl: currentVideo,
           foregroundPointCoordinates: selectedPoints.map(point => ({
            x: point.x,
            y: point.y
          })),
          backgroundPointCoordinates: selectGreenPoints.map(point => ({
             x: point.x,
             y: point.y
          })),
          startStamp,
          endStamp
         };
        const response = await clickSelect(requestData);
        console.log('点选任务提交成功:', response);
        
        // 更新片段状态为已提交
        if (response?.data?.operId && onSegmentStateUpdate) {
          onSegmentStateUpdate('TRACKING', response.data.operId);
        }
      }
      if (selectedTool === 'graphic' && selectionRects.length > 0) {
        // 点选工具提交（包括内容擦除）
        const requestData = {
          targetVideoUrl: currentVideo,
          coordinates: selectionRects.map(point => ({
            tlx: point.tlx,
            tly: point.tly,
            brx: point.brx,
            bry: point.bry
          })),
          startStamp,
          endStamp
        };
       const response = await boxSelect(requestData);
       console.log('框选任务提交成功:', response);
       
       // 更新片段状态为已提交
      if (response?.data?.operId && onSegmentStateUpdate) {
        onSegmentStateUpdate('TRACKING', response.data.operId);
      }
     }
     if(selectedTool === 'brush'&&brushStrokes.length > 0) {
       // 获取当前离屏canvas图片（原尺寸）
       const canvasImageData = canvasDrawingRef.current?.getCanvasImage();
       if (!canvasImageData) {
         console.error('无法获取canvas图片数据');
         return;
       }
       
       // 将base64转换为File对象
       const base64ToFile = (base64Data, fileName) => {
         const arr = base64Data.split(',');
         const mime = arr[0].match(/:(.*?);/)[1];
         const bstr = atob(arr[1]);
         let n = bstr.length;
         const u8arr = new Uint8Array(n);
         while (n--) {
           u8arr[n] = bstr.charCodeAt(n);
         }
         return new File([u8arr], fileName, { type: mime });
       };
       
       const maskFile = base64ToFile(canvasImageData, `mask_${Date.now()}.png`);
       // 上传mask图片
       const uploadResult = await uploadFile({
         fileInstance: maskFile,
         name: maskFile.name
       });
       
       if (!uploadResult.success) {
         console.error('mask图片上传失败:', uploadResult.error);
         return;
       }
       
       // 涂选工具提交（包括内容擦除）
       const requestData = {
        targetVideoUrl: currentVideo,
        maskImageUrl: uploadResult.url,
        startStamp,
        endStamp
       };
      const response = await smearSelect(requestData);
       console.log('涂选任务提交成功:', response);
       
      // 更新片段状态为已提交
      if (response?.data?.operId && onSegmentStateUpdate) {
        onSegmentStateUpdate('TRACKING', response.data.operId);
      }
     }
     if (selectedTool === 'segmentation' && erasureText.trim() !== '') {
       // 分割工具提交
       const requestData = {
        erasureText: erasureText.trim(),
        targetVideoUrl: currentVideo,
        startStamp,
        endStamp
       };
       const response = await partitionSelect(requestData);
       console.log('分割任务提交成功:', response);
       
      // 更新片段状态为已提交
      if (response?.data?.operId && onSegmentStateUpdate) {
        onSegmentStateUpdate('TRACKING', response.data.operId);
      }
     }
     if (selectedTool === 'preset' && selectedPreset) {
       // 预设主体选择提交
       const requestData = {
        subjectType: selectedPreset === 'person' ? 'human' : 'common',
        targetVideoUrl: currentVideo,
        startStamp,
        endStamp
       };
       const response = await mainSelect(requestData);
       console.log('预设主体任务提交成功:', response);
       
      // 更新片段状态为已提交
      if (response?.data?.operId && onSegmentStateUpdate) {
        onSegmentStateUpdate('TRACKING', response.data.operId);
      }
     }
    } catch (error) {
      console.error('提交任务失败:', error);
    }
  };
  
  const handleHistoryModalCancel = useCallback(() => {
    setHistoryModal(false);
  }, []);
  
  const handleHistoryModalConfirm = useCallback(() => {
    setHistoryModal(false);
  }, []);
  
  const handleToolClick = useCallback((toolKey) => {
    onToolChange?.(toolKey);
  }, [onToolChange]);
  
  // 防止页面刷新时的提示
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      e.preventDefault();
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []);
  
  return (
    <div className={styles.mainEdit}>
      <div className={styles.top}>
        <div className={styles.header}>
          <div className={styles.title}>影视后期ROTO</div>
        </div>
        <TimeRangeSelector 
            startTime={startTime}
            endTime={endTime}
            disabled={true}
            // current={current}
            onStartTimeChange={(time) => {
                setStartTime(time);
            }}
            onEndTimeChange={(time) => {
                setEndTime(time);
            }}
        />
        {step===1 && (
          <>
            <div className={styles.imageContainer}>
              <ToolButtons 
                selectedTool={selectedTool} 
                onToolClick={selectedPreviewMode == 'original'?handleToolClick:''} 
              />
              {selectedTool=='brush'&&(
                <div className={styles.brushSizeContainer}>
                  <div className={styles.brushSizeWrapper}>
                    <div>画笔尺寸</div>
                    <div className={styles.brushSizeSliderContainer}>
                      <div className={styles.brushSizeIcon}>
                        <div className={styles.brushSizeIconSmall}></div>
                      </div>
                      <Slider
                        className={styles.slider}
                        min={10}
                        max={200}
                        value={toolSize}
                        onChange={onToolSizeChange}
                      />
                      <div className={styles.brushSizeIcon}>
                        <div className={styles.brushSizeIconLarge}></div>
                      </div>
                    </div>
                    <div className={styles.brushSizeInput}>
                      <IconMinus 
                        onClick={() => onToolSizeChange(Math.max(10, toolSize - 1))}
                        style={{ cursor: 'pointer' }}
                      />
                      <div>{toolSize}px</div>
                      <IconPlus 
                        onClick={() => onToolSizeChange(Math.min(200, toolSize + 1))}
                        style={{ cursor: 'pointer' }}
                      />
                    </div>
                  </div>
                </div>
              )}
              {selectedTool=='segmentation'&&(
                <TextArea 
                  style={{padding:'8px'}}
                  placeholder='请输入您想要更改的内容...'
                  value={erasureText}
                  onChange={(value) => setErasureText(value)}
                />
              )}
              {selectedTool=='preset'&&(
                <div className={styles.presetContainer}>
                  <div 
                    className={`${styles.presetItem} ${selectedPreset === 'person' ? styles.selected : ''}`}
                    onClick={() => handlePresetClick('person')}
                  >
                    <Image
                      src={person_Subject}
                      className={styles.img}
                      preview={false}
                      draggable={false}
                    />
                    <div className={styles.presetLabel}>人</div>
                  </div>
                  <div 
                    className={`${styles.presetItem} ${selectedPreset === 'general' ? styles.selected : ''}`}
                    onClick={() => handlePresetClick('general')}
                  >
                    <Image
                      src={general_Subject}
                      className={styles.img}
                      preview={false}
                      draggable={false}
                    />
                    <div className={styles.presetLabel}>通用</div>
                  </div>
                </div>
              )}
            </div>
          </>
        )}
        {step===1 && (
          <div className={styles.submitButtonContainer}>
            <Button 
              className={`button buttonPrimary ${styles.submitButton}`}
              disabled={!hasDataToSubmit||!selectedSegmentId || !segments.find(segment => segment.selectId === selectedSegmentId && (['TRACK_FAILED','TRACK_SUCCESS'].includes(segment.state)||!segment.state))}
              onClick={handleSubmitTask}
            >
              {(() => {
                const selectedSegment = segments.find(segment => segment.selectId === selectedSegmentId);
                if (!selectedSegment) return '提交分割任务';
                switch (selectedSegment.state) {
                  case 'SUBMITTED':
                  return '提交中...';
                case 'TRACKING':
                  return '分割中...';
                case 'REPLACEING':
                  return '背景替换中...';
                case 'ERASING':
                  return '内容擦除中...';
                case 'TRACK_FAILED':
                  return '重新提交';
                default:
                  return '提交分割任务';
                }
              })()} 
            </Button>
            <Button
              className={`button buttonFailed ${styles.submitButton}`}
              disabled={!selectedSegmentId}
              onClick={() => {
                if (selectedSegmentId && onDeleteSegment) {
                  onDeleteSegment(selectedSegmentId);
                }
              }}
            >
              删除此片段
            </Button>
          </div>
        )}
        {step===1&&(
          <>
            <div className={styles.titleSection}>分割片段<span>已经应用分割片段</span></div>
            <div 
              className={styles.area}
            >
              {showAppliedProject && <div className={styles.head} onClick={() => setShowAppliedProject(false)}>
                <Image
                  src={vector}
                  preview={false}
                  className={styles.vector}
                  draggable={false}
                />
                已应用片段
              </div>}
              <div className={styles.areaContent}>
                 {!showAppliedProject && (
                   <div 
                     className={`${styles.layerItem} ${selectedPreviewMode === 'result' ? styles.disabled : ''}`} 
                     onClick={selectedPreviewMode === 'result' ? undefined : onAddSegment}
                     style={{
                       opacity: selectedPreviewMode === 'result' ? 0.5 : 1,
                       cursor: selectedPreviewMode === 'result' ? 'not-allowed' : 'pointer'
                     }}
                   >
                     <div className={`${styles.uploadSection}` }  >
                       <div className={styles.uploadPlaceholder}>
                         <Image
                           src={add_gray}
                           preview={false}
                           className={styles.uploadIcon}
                           draggable={false}
                         />
                         <div className={styles.uploadText}>
                           新增分割片段
                         </div>
                       </div>
                     </div>
                   </div>
                 )}
                 {/* 根据showAppliedProject状态过滤显示的片段 */}
                 {segments
                   .filter(segment => showAppliedProject ? segment.state === 'SYNTHETIC_SUCCESS' : segment.state !== 'SYNTHETIC_SUCCESS')
                   .map((segment) => (
                  <div className={`${styles.layerItem} ${segment.selectId === selectedSegmentId ? styles.segmentItemSelected : ''} ${segment.state === 'TRACK_FAILED' ? styles.segmentFailed : ''}`}
                  key={segment.selectId}
                  onClick={() => onSegmentClick?.(segment.selectId)}>
                    <Image
                      src={segment.coverImgUrl}
                      className={styles.img}
                      preview={false}
                      draggable={false}
                    />
                    {segment.state === 'TRACK_SUCCESS' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>分割成功</div>
                      </div>
                    )}
                    {segment.state === 'TRACK_FAILED' && (
                      <div className={styles.overlay}>
                        <div className={styles.failedText}>分割失败</div>
                      </div>
                    )}
                    {segment.state === 'ERAS_SUCCESS' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>擦除成功</div>
                      </div>
                    )}
                    {segment.state === 'REPLACE_SUCCESS' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>背景替换成功</div>
                      </div>
                    )}
                    {segment.state === 'SYNTHETIC_SUCCESS' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>合成成功</div>
                      </div>
                    )}
                    {segment.state === 'SUBMITTED' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>提交中...</div>
                      </div>
                    )}
                    {segment.state === 'TRACKING' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>分割中...</div>
                      </div>
                    )}
                    {segment.state === 'ERASING' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>擦除中...</div>
                      </div>
                    )}
                    {segment.state === 'REPLACEING' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>背景替换中...</div>
                      </div>
                    )}
                    {segment.state === 'SYNTHETICING' && (
                      <div className={styles.overlay}>
                        <div className={styles.text}>合成中...</div>
                      </div>
                    )}
                  </div>)
                )}
                {segments.some(segment => segment.state === 'SYNTHETIC_SUCCESS') && !showAppliedProject &&<div className={`${styles.layerItem}`}>
                  <div className={`${styles.uploadSection}` } onClick={() => setShowAppliedProject(true)}>
                    <div className={styles.uploadPlaceholder}>
                      <Image
                        src={folder}
                        preview={false}
                        className={styles.uploadIcon}
                        draggable={false}
                      />
                      <div className={styles.uploadText}>
                        已应用项目
                      </div>
                    </div>
                  </div>
                </div>}
              </div>
            </div>
          </>
        )}
        <div className={styles.bottom}>
          <div style={{display:'flex',gap:'16px'}}>
            {false&&<Button
              style={step===1? {flex:'1'} : {width:'154px'}}
              className='button buttonDefault'
              onClick={handlePrevStep}
            >
              上一步
            </Button>}
            <Button
              style={{width:'172px'}}
              className='button buttonPrimary'
              onClick={handleSyntheticVideo}
              loading={isGenerating}
              disabled={isGenerating || !segments.some(segment => segment.state === 'ERAS_SUCCESS' || segment.state === 'REPLACE_SUCCESS')}
            >
              应用分割片段
            </Button>
          </div>
        </div>
      </div>
      <HistoryModal 
          visible={historyModal}
          onCancel={handleHistoryModalCancel}
          onConfirm={handleHistoryModalConfirm}
        />
    </div>
  )
}